<template>
    <a-spin :spinning="confirmLoading">
      <j-form-container :disabled="formDisabled">
        <a-form-model :model="form" slot="detail" :rules="rules" ref="dynamicValidateForm">
           <a-row :gutter="24">
             <a-col :span="24">
              <a-form-model-item 
                label="年份" 
                :labelCol="{span: 2}" 
                :wrapperCol="{span: 18}" 
                style="margin:0 0 15px 10px"
                prop="year"
                :rules="{
                    required: true,
                    message: '请选择年份',
                    trigger: 'change',
                }"
                >
                  <a-date-picker
                     :disabled="isShow"
                      :allowClear="false"
                      placeholder="请选择年份"
                      format="YYYY"
                      mode="year"
                      :value="year"
                      :open="open"
                      @openChange="openChange"
                      @panelChange="panelChange"
                  />
              </a-form-model-item>
             </a-col>
             <div v-for="(item,index) in form.marketAverageList" :key="item">
                    <a-col :span="11">
                      <a-form-model-item 
                        style="margin-bottom:20px"
                        label="品种名" 
                        :labelCol="{span: 5}" 
                        :wrapperCol="{span: 16}" 
                        :prop="'marketAverageList.' + index + '.varietyId' "
                        :rules="{
                            required: true,
                            message: '请选择品种',
                            trigger: 'blur',
                        }"
                        >
                        <a-select
                            :disabled="isShow"
                            v-model="item.varietyId"
                            placeholder="请选择品种"
                        >
                            <a-select-option
                            v-for="(item, index) in varietyOptions"
                            :key="index"
                            :value="item.value"
                            >
                            {{ item.title }}
                            </a-select-option>
                        </a-select>
                      </a-form-model-item>
                    </a-col>
                    <a-col :span="11">
                        <a-form-model-item
                        style="margin-bottom:20px"
                        label="均价（元/斤）" 
                        :labelCol="{span: 8}" 
                        :wrapperCol="{span: 16}"
                        :prop=" 'marketAverageList.' + index + '.average' "
                        :rules="[{
                            required: true,
                            message: '请输入均价',
                            trigger: 'blur',
                          },
                          {validator:handlePlantNumCheck}
                        ]"
                        >
                        <a-input-number
                           :disabled="isShow"
                            style="width:100%"
                            :min="0"
                            placeholder="请输入均价"
                            v-model="item.average"
                            :precision="1"
                        />
                        </a-form-model-item>
                    </a-col>
                    <a-col :span="2" style="padding-left: 0px">
                        <a-form-model-item :labelCol="{span: 0}" :wrapperCol="{span: 14}">
                            <a-icon type="minus-circle" style="font-size:16px;color:#D93026;margin-top:10px" @click="delItem(form.marketAverageList,index)" v-if="!isShow"></a-icon>
                        </a-form-model-item>
                    </a-col>
            </div>
            <a-button type="dashed" style="width:260px;margin:10px 0 0 88px" icon="plus" @click="addDomain" v-if="!isShow">
                添加品种
            </a-button>
          </a-row>
        </a-form-model>
      </j-form-container>
    </a-spin>
</template>

<script>
  import { httpAction, getAction } from '@/api/manage'
  import pick from 'lodash.pick'
  import JFormContainer from '@/components/jeecg/JFormContainer'
  import JDictSelectTag from "@/components/dict/JDictSelectTag"
  import JMultiSelectTag from "@/components/dict/JMultiSelectTag"
   import moment from 'moment';
  export default {
    name: 'marketAvPriceForm',
    components: {
      JFormContainer,
      JDictSelectTag,
      JMultiSelectTag,
    },
    props: {
      //流程表单data
      formData: {
        type: Object,
        default: ()=>{},
        required: false
      },
      //表单模式：true流程表单 false普通表单
      formBpm: {
        type: Boolean,
        default: false,
        required: false
      },
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      },
       //详情
      isShow: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    data () {
      return {
        oldYear:undefined,
        isAdd:true,
        varietyOptions:[],
        year:'',
        open:false,
        result:{},
        userId:'',
        seePassword:true,
        positionList:[],
        tqppSystemList:[],//权限列表
        form: {
            year:'',
             marketAverageList:[
            {
                varietyId: undefined,
                average: undefined
            }
        ],
        },
        model: {},
        labelCol: {
          xs: { span: 3 },
          sm: { span: 2 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 10 },
        },
        confirmLoading: false,
        rules: {},
        url: {
          add: "/marketAverage/add",
          edit: "/marketAverage/update",
          queryById: "/marketAverage/queryDetailBYear"
        }
      }
    },
    computed: {
      formDisabled(){
        if(this.formBpm===true){
          if(this.formData.disabled===false){
            return false
          }
          return true
        }
        return this.disabled
      },
      showFlowSubmitButton(){
        if(this.formBpm===true){
          if(this.formData.disabled===false){
            return true
          }
        }
        return false
      }
    },
    created () {
      //如果是流程中表单，则需要加载流程表单data
      this.showFlowData();
    },
    mounted () {
        this.getVarietyList()
    },
    methods: {
      handlePlantNumCheck(rule,value,callback){
        if (!value || new RegExp(/^\d+$|^\d+[.]?\d+$/).test(value)){
          callback();
        }else{
          callback("仅可输入数字!");
        }
      },
      openChange(status) {
        if (status) {
          this.open = true;
        } else {
          this.open = false;
        }
      },
      panelChange(value){
          const yearEnd = moment().endOf('year'); 
          if(value > yearEnd){
            return  this.$message.error('不能大于当前年份')
          }
          this.year = value.toString().substring(11, 15)
          this.form.year = this.year
          this.open = false;
      },
      addDomain() {
        this.form.marketAverageList.push({
          varietyId: undefined,
          average:undefined,
        });
      },
      delItem(items, index) {
        this.$confirm({
          title: '提示',
          content: '确定删除该条数据吗 ?',
          onOk() {
          items.splice(index, 1)
          },
          onCancel() {
          }
        })
      },
      async getVarietyList() {
        const res = await getAction('/sys/dict/getDictItems/txpp_category')
        if(res.success){
          this.varietyOptions = res.result
        }else{
          this.$message.error(res.message) 
        }
      },
      add() {
        this.isAdd = true
        this.edit({})
      },
      edit(record) {
          this.$nextTick(()=>{
            this.$refs.dynamicValidateForm.resetFields()
          })
          if(!record.year){
            this.form.year = ''
            this.year = ''
            this.form.marketAverageList = []
          }else{
            this.oldYear = record.year
            this.form = Object.assign({}, record)
            this.year = moment(record.year,'YYYY')
            this.isAdd = false
          }
          this.visible = true
      },
      //渲染流程表单数据
      showFlowData(){
        if(this.formBpm === true){
          let params = {id:this.formData.id};
          getAction(this.url.queryById,params).then((res)=>{
            if(res.success){
              this.edit(res.result,false);
            }
          });
        }
      },
      submitForm () {
        const that = this;
        // 触发表单验证
        this.$refs.dynamicValidateForm.validate((valid) => {
              if (valid) {
                if(this.form.marketAverageList.length===0){
                  this.$message.warning('请至少添加一条品种数据')
                }else{
                  this.form.marketAverageList.map(item=>{
                    item.year = this.form.year
                  })
                  that.confirmLoading = true;
                  this.$emit('loading',that.confirmLoading)
                  let httpurl = '';
                  let method = 'post';
                  let formData
                  if(this.isAdd){
                    httpurl+=this.url.add;
                    formData = this.form.marketAverageList
                  }else{
                    httpurl+=this.url.edit;
                    formData = {}
                    formData.oldYear = this.oldYear
                    formData.nowYear = Number(this.form.year)
                    formData.list = this.form.marketAverageList
                  }
                  httpAction(httpurl,formData,method).then((res)=>{
                    if(res.success){
                      that.$message.success(res.message);
                      that.$emit('ok');
                    }else{
                      that.$message.warning(res.message);
                    }
                  }).finally(() => {
                    that.confirmLoading = false;
                    this.$emit('loading',that.confirmLoading)
                  })
                }
              }else{
                 console.log('error submit!!');
                 return false;
            }
        })
      },
      popupCallback(row){
        this.form.setFieldsValue(pick(row,
          'year',
          'marketAverageList'
        ))
      },
    }
  }
</script>
<style lang="less" scoped>
.ant-calendar-picker{
    width: 250.44px;
}
/deep/.varietyForm{
.ant-table-tbody > tr::hover{
    background: transparent !important;
}
.ant-table-tbody > tr > td {
    border-bottom: none;
}
.ant-table-tbody .ant-table-row td {
    padding-top: 5px !important;
    padding-bottom: 5px !important;
}
.ant-table-thead{
    display: none;
}
}
.ant-checkbox-wrapper{
margin: 10px 0;
}
.ant-radio-group{
padding: 0 10px;
}
.ant-form-item-control{
  line-height: 0px!important
}
.ant-col-sm-5{
  width: 100px;
}
.projectstyle{
.ant-col-sm-16{
  width: 88%;
  .ant-form-item-control{
    .ant-form-item-children{
      >div{
        width: 95% !important;
      }
    }
  }
}
}
</style>